import React from 'react';
import ReactECharts from 'echarts-for-react';
import { Relationship, Node } from 'types/tech-insight';

interface TechGraphProps {
  nodes: Node[];
  relationships: Relationship[];
  categories: string[];
  size?: 'small' | 'large';
  title?: string;
}

const TechGraph: React.FC<TechGraphProps> = ({
  nodes,
  relationships,
  categories = [],
  size = 'large',
  title = '技术关联图谱',
}) => {
  const option = {
    // title: {
    //   text: title,
    // },
    tooltip: {
      show: true,
      trigger: 'item',
      formatter: (params: {
        dataType: string;
        name: string;
        data: {
          sourceName: string;
          targetName: string;
          description: string;
        };
      }) => {
        // 只显示关系的名称
        if (params.dataType === 'edge') {
          return `
            <div>
              <p>关系： ${params.name}</p>
              <p>关系源：${params.data.sourceName}</p>
              <p>关系目的：${params.data.targetName}</p>
            </div>
          `;
        }
        return `
          <div>
            <p>节点名称： ${params.name}</p>
            <p>节点详情：${params.data.description || '无'}</p>
          </div>
        `;
      },
    },
    legend: {
      width: '100%', // 宽度占满容器
      orient: 'horizontal', // 水平排列
      data: categories,
    },
    series: [
      {
        type: 'graph',
        layout: 'force', // 布局方式 'none'：无布局。 'circular'：环形布局。 'force'：力导向布局（默认）
        data: nodes.map((node) => ({
          id: node.nodeId,
          name: node.name,
          description: node.description,
          category: node.category,
          symbolSize: node.value || 20, // 节点大小
          value: node.value || 1,
        })),
        links: relationships.map((relationship) => ({
          id: relationship.name,
          source: relationship.sourceID,
          target: relationship.targetID,
          sourceName: relationship.source,
          targetName: relationship.target,
          value: relationship.value || 2,
        })),
        categories: categories.map((category) => ({ name: category })),
        roam: true, // 是否开启鼠标缩放和平移漫游
        zoom: 0.8, // 设置初始缩放比例
        label: {
          show: true,
          position: 'right',
          formatter: '{b}',
          distance: 5, // 调整标签距离
        },
        force: {
          repulsion: 200, // 节点之间的斥力
          edgeLength: size === 'large' ? [100, 200] : [100, 100], // 边长度
          gravity: 0.2, // 调整重力
        },
        emphasis: {
          focus: 'adjacency',
        },
        lineStyle: {
          width: 2, // 默认宽度
          color: 'source',
          curveness: 0.3,
          opacity: 0.8, // 增加透明度
        },
      },
    ],
  };

  const height = size === 'large' ? 600 : 400;

  return <ReactECharts option={option} style={{ height }} />;
};

export default TechGraph;
